import SwiftUI

struct ChatView: View {
    @State private var messages: [Message] = []
    @State private var inputText: String = ""
    @State private var keyboardHeight: CGFloat = 0
    @Environment(\.presentationMode) var presentationMode
    @State private var isSend = true
    var girlName:String
    var body: some View {
        VStack(spacing: 0) {
            Back(title: "Chatting with \(girlName)", onBackTap: {
                self.presentationMode.wrappedValue.dismiss()
            }, onImageTap: {})
            
            ScrollViewReader { scrollViewProxy in
                ScrollView {
                    VStack(spacing: 10) {
                        ForEach(messages) { message in
                            MessageRow(message: message, isUser: message.isUser,name:girlName)
                                .id(message.id)
                        }
                    }
                    .padding(.top, 20) // 固定顶部填充
                    .padding(.horizontal)
                    .background(Color("mainback"))
                }
                .onChange(of: messages) { _ in
                    if let lastMessage = messages.last {
                        withAnimation {
                            scrollViewProxy.scrollTo(lastMessage.id, anchor: .bottom)
                        }
                    }
                }
                .onAppear {
                    if let lastMessage = messages.last {
                        withAnimation {
                            scrollViewProxy.scrollTo(lastMessage.id, anchor: .bottom)
                        }
                    }
                }
            }
            
            HStack {
                ZStack {
                    TextField("Type a message", text: $inputText)
                        .textFieldStyle(PlainTextFieldStyle())
                        .padding(EdgeInsets(top: 8, leading: 8, bottom: 8, trailing: 40))
                        .foregroundColor(Color.white)
                        .cornerRadius(8)
                        .overlay(
                            RoundedRectangle(cornerRadius: 8)
                                .stroke(Color.blue, lineWidth: 1)
                        )
                        .frame(minHeight: 30)
                    
                    HStack {
                        Spacer()
                        if isSend && UserDefaultsManager.shared.isChatMessageCountGreaterThanTen(){
                            Image("send")
                                .padding(.trailing, 5)
                                .onTapGesture {
                                    sendMessage()
                                }
                        }
                    }
                }
            }
            .padding()
            .padding(.bottom, keyboardHeight)
            .animation(.easeOut(duration: 0.16))
            .onAppear {
                NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillShowNotification, object: nil, queue: .main) { notification in
                    let value = notification.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! CGRect
                    keyboardHeight = value.height - (UIApplication.shared.windows.first?.safeAreaInsets.bottom ?? 0)
                }
                NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillHideNotification, object: nil, queue: .main) { _ in
                    keyboardHeight = 0
                }
                
                loadMessages()
            }
        }
        .navigationViewStyle(StackNavigationViewStyle())

        .navigationBarHidden(true)
        .background(Color("mainback"))
        .edgesIgnoringSafeArea(.bottom)
    }
    
    private func loadMessages() {
        let jsonString = UserDefaultsManager.shared.getChatMessagesJSON()
        
        if !jsonString.isEmpty {
            if let data = jsonString.data(using: .utf8) {
                do {
                    let jsonMessages = try JSONDecoder().decode([JSONMessage].self, from: data)
                    self.messages = jsonMessages.map { Message(text: $0.content, isUser: $0.role == "user") }
                } catch {
                    print("Error decoding JSON: \(error)")
                }
            }
        } else {
            receiveMessageFromFriend()
        }
    }
    
    private func receiveMessageFromFriend() {
        // Simulate receiving a message from friend
        let receivedMessage = Message(text: "Hello! How are you?", isUser: false)
        messages.append(receivedMessage)
        UserDefaultsManager.shared.saveChatMessage(role: receivedMessage.isUser, content: receivedMessage.text)
    }
    
    private func sendMessage() {
        guard !inputText.isEmpty else { return }
        self.isSend = false
        let userMessage = Message(text: inputText, isUser: true)
        messages.append(userMessage)
        UserDefaultsManager.shared.saveChatMessage(role: userMessage.isUser, content: userMessage.text)
        inputText = ""
        
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            postRequest(with: UserDefaultsManager.shared.getChatMessagesJSON()) { result in
                switch result {
                case .success(let responseString):
                    self.isSend  = true
                    let responseMessage = Message(text: responseString, isUser: false)
                    UserDefaultsManager.shared.saveChatMessage(role: false, content: responseString)
                    messages.append(responseMessage)
                case .failure(let error):
                    print("Error: \(error)")
                }
            }
        }
    }
}

struct MessageRow: View {
    let message: Message
    let isUser: Bool
    var name:String
    var body: some View {
        HStack(alignment: .top) {
            if !isUser {
                Image(imageName(for:name))
                    .resizable()
                    .frame(width: 40, height: 40)
                    .clipShape(Circle())
                    .padding(.trailing, 10)
            } else {
                Spacer()
            }
            
            VStack(alignment: isUser ? .trailing : .leading, spacing: 4) {
                Text(message.text)
                    .padding(.horizontal, 12)
                    .padding(.vertical, 8)
                    .foregroundColor(.white)
                    .background(isUser ? Color.blue : Color.gray)
                    .cornerRadius(10)
                
                Text(message.timestamp)
                    .font(.caption)
                    .foregroundColor(.gray)
                    .padding(.horizontal, 10)
                    .padding(.top, 2)
            }
            .frame(maxWidth: .infinity, alignment: isUser ? .trailing : .leading)
            
            if isUser {
                Image("icon")
                    .resizable()
                    .frame(width: 40, height: 40)
                    .clipShape(Circle())
                    .padding(.leading, 10)
            } else {
                Spacer()
            }
        }
        .frame(maxWidth: .infinity, alignment: isUser ? .trailing : .leading)
    }
    func imageName(for name: String) -> String {
        if let girl = girls.first(where: { $0.name == name }) {
            return girl.imageName
        } else {
            return "g1" // 默认返回的图片名称
        }
    }
}

struct Message: Identifiable, Equatable {
    let id = UUID()
    let text: String
    let isUser: Bool
    let timestamp: String = {
        let formatter = DateFormatter()
        formatter.dateFormat = "HH:mm"
        return formatter.string(from: Date())
    }()
}

struct JSONMessage: Codable {
    let content: String
    let role: String
}

struct ChatView_Previews: PreviewProvider {
    static var previews: some View {
        ChatView(girlName: "Lily")
    }
}
